import 'package:flutter/material.dart';
import 'package:gesture_password/gesture_password.dart';
import 'package:gesture_password/mini_gesture_password.dart';
import 'function.dart';
import 'package:flutter/cupertino.dart';
import 'package:local_auth/local_auth.dart';
import 'package:local_auth/auth_strings.dart';
import 'dart:async';
import 'package:flutter/services.dart';
class CheckPassword extends StatefulWidget {
  CheckPassword(this.mainColor, this.type);
  final Color mainColor;
  //1 设置页面进入 2只有手势 3只有指纹 4 手势+指纹
  final int type;
  @override
  _CheckPasswordState createState() => new _CheckPasswordState();
}

class _CheckPasswordState extends State<CheckPassword> {
  @override
  initState() {
    super.initState();
    initPass();
  }

  String tip = "绘制解锁图案";
  bool err = false;
  String password = "";
  GlobalKey<MiniGesturePasswordState> miniGesturePassword = new GlobalKey<MiniGesturePasswordState>();

  GlobalKey<ScaffoldState> scaffoldState = new GlobalKey<ScaffoldState>();
  initPass() async {
    print(widget.type);
    this.password = await getStorage("gesture");
    if (widget.type == 3 || widget.type == 4) {
      checkFinger();
    }
  }

  Future<bool> willPop() {
    if(widget.type==1){
      return new Future.value(true);
    }else{
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: const Text('退出玩客随行？'),
            actions: <Widget>[
              FlatButton(
                child: Text('退出',style: new TextStyle(fontWeight: FontWeight.bold,color: Colors.red),),
                onPressed: () {
                  Navigator.of(context).pop();
                  SystemNavigator.pop();
                },
              ),
              FlatButton(
                child: Text('取消'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        },
      );
      return new Future.value(false);
    }

  }

  checkFinger() async {
    var localAuth = new LocalAuthentication();
    bool didAuthenticate = await localAuth.authenticateWithBiometrics(
      localizedReason: '请验证指纹',
      androidAuthStrings: new AndroidAuthMessages(
        cancelButton: "取消",
        goToSettingsButton: "设置指纹",
        goToSettingsDescription: "需先设置指纹后重新验证",
        fingerprintHint: "验证指纹",
        fingerprintSuccess: "指纹验证成功",
        signInTitle: "请验证指纹",
        fingerprintNotRecognized: "指纹无效，请重新验证",
        fingerprintRequiredTitle: "尚未设置指纹",
      ),
      iOSAuthStrings: new IOSAuthMessages(
        cancelButton: '取消',
        goToSettingsButton: '设置',
        goToSettingsDescription: '需先设置指纹重新验证',
        lockOut: '请重新验证指纹',
      ),
    );
    if (didAuthenticate) {
      Navigator.of(context).pop();
    }
  }

  @override
  Widget build(BuildContext context) {
    return new WillPopScope(
        child: Scaffold(
          key: scaffoldState,
          appBar: new CupertinoNavigationBar(
            actionsForegroundColor: Colors.white,
            backgroundColor: widget.mainColor,
            border: new Border(bottom: BorderSide.none),
            middle: new Text(
              widget.type == 1 || widget.type == 2 ? "验证手势密码" : widget.type == 4 ? "验证指纹" : "安全验证",
              style: new TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.normal,
              ),
            ),
            automaticallyImplyLeading: widget.type == 1,
          ),
          body: widget.type != 4
              ? new Column(
            children: <Widget>[
              new Center(
                child: new Column(
                  children: <Widget>[
                    new SizedBox(
                      height: 50.0,
                    ),
                    new MiniGesturePassword(
                      key: miniGesturePassword,
                      attribute: new MiniItemAttribute(
                        normalColor: Colors.black54,
                        selectedColor: widget.mainColor,
                        smallCircleR: 4.0,
                      ),
                    ),
                    new SizedBox(
                      height: 10.0,
                    ),
                    new Text(
                      this.tip,
                      style: new TextStyle(color: this.err ? Colors.red : Colors.black54),
                    )
                  ],
                ),
              ),
              new LayoutBuilder(
                builder: (BuildContext ctx, BoxConstraints constraints) {
                  return new Container(
                    margin: const EdgeInsets.only(top: 20.0),
                    child: new GesturePassword(
                      height: MediaQuery.of(context).size.width,
                      attribute: new ItemAttribute(
                        normalColor: Colors.black54,
                        selectedColor: widget.mainColor,
                      ),
                      successCallback: (pass) {
                        if (password == pass) {
                          Navigator.of(context).pop(true);
                        } else {
                          tip = "密码有误，请重新绘制";
                          err = true;
                        }
                        setState(() {});
                        miniGesturePassword.currentState?.setSelected('');
                      },
                      failCallback: () {
                        tip = "至少连接4个点，请重新绘制";
                        err = true;
                        setState(() {});
                        miniGesturePassword.currentState?.setSelected('');
                      },
                      selectedCallback: (str) {
                        miniGesturePassword.currentState?.setSelected(str);
                      },
                    ),
                  );
                },
              ),
              widget.type==4?new FlatButton(
                onPressed: checkFinger,
                child: new Text("点击重新验证指纹"),
              ):new Text(""),
            ],
          )
              : new Center(
            child: new CupertinoButton(
              child: new Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  new Icon(
                    Icons.fingerprint,
                    size: 60.0,
                    color: widget.mainColor,
                  ),
                  new Text("点击重新验证指纹",style: new TextStyle(color:widget.mainColor,fontSize: 12.0),),
                ],
              ),
              onPressed: checkFinger,
            ),
          ),
        ),
        onWillPop: willPop,
      );
  }
}
